const jsonp = ({ url, success, faild, data }) => {
    // 配置
    const { callbackName } = options;
    window[callbackName] = (params) => {
        if(params !== null){
            success(params);
        }else{
            failure(params);
        }

        // 2.1 删除当前脚本标签
        scriptE.remove();
        // 2.2 将创建的全局函数设为null
        window[callBackName] = null;
    }

    // 3. 取出url地址
    let jsonpUrl;
    if (options.data !== undefined) {
        jsonpUrl = options.url + '?' + options.data + '&callBack=' + callBackName;
    } else {
        jsonpUrl = options.url + '?callBack=' + callBackName;
    }

    // 4. 创建script标签
    let scriptE = document.createElement('script');
    scriptE.src = jsonpUrl;
    document.body.appendChild(scriptE);
}

/**
* jsonp获取请求数据
* @param {string}url
* @param {object}params
* @param {function}callback
*/
function jsonpPromise({ url, params, callback }) {
    return new Promise((resolve, reject) => {
        let script = document.createElement('script');
        params = JSON.parse(JSON.stringify(params));
        let arrs = [];
        for (let key in params) {
            arrs.push(`${key}=${params[key]}`);
        }
        arrs.push(`callback=${callback}`);
        script.src = `${url}?${arrs.join('&')}`;
        document.body.appendChild(script);
        window[callback] = function (data) {
            resolve(data);
            document.body.removeChild(script);
        }
    })
}

